package com.wm.walmart.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wm.walmart.util.JwtToken;
import com.wm.walmart.util.Token;

@Component
public class LoginInterceptor implements HandlerInterceptor {

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 允许跨域的主机地址
		response.setHeader("Access-Control-Allow-Origin", "*");
		// 获取请求路径，例如：/ent/list
		String requestUri = request.getRequestURI();
		List<String> excludedUris = new ArrayList<String>();
		excludedUris.add("login/logins");
		for (String uri : excludedUris) {
			if (requestUri.contains(uri)) {
				return true;
			}
		}
		// 获取用户每次请求时，携带的tokenId信息
		String tokenId = request.getParameter("tokenId");
		if (tokenId != null && !tokenId.equals("")) {
			Token token = JwtToken.unsign(tokenId, Token.class);
			if (token != null) {// 说明用户已登录并且token有效
				return true;
			}
		}
		return false;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
